package com.bauer.module.framework.context;

import com.bauer.module.framework.constant.Constant;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @Author ：rui.wei
 * @Date ：Created in 12:26 2019/4/15
 * @Description： spring boot  使用了springboot factories 功能  类似于spi
 */
public class AppConfigRunListener implements SpringApplicationRunListener {

    private static final String DEFAULT_WINDOS_LOG_PATH = "C://appLog";

    private static final String DEFAULT_LINUX_LOG_PATH = "/var/log";

    private static final String DEFAULT_LOG_LEVEL = "INFO";

    private static final String DEFAULT_APP_NAME = "simpleApp";

    private static final String DEFAULT_LOG_FILE = "classpath:log/logback-spring.xml";


    /**
     * 实现SpringApplicationRunListener 必须创建此构造方法
     */
    public AppConfigRunListener(SpringApplication springApplication, String args[]) {

    }

    @Override
    public void starting() {
        setEnvProps();
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        String appName = environment.getProperty(Constant.APP_NAME);
        System.out.println(environment.getProperty("spring.config.location"));
        if (appName == null) {
            //应用名称存在设置默认名称
            System.setProperty(Constant.APP_NAME, DEFAULT_APP_NAME + RandomUtils.nextInt(0, 20));
        } else {
            System.setProperty(Constant.APP_NAME, appName);
        }
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {

    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {

    }

    @Override
    public void started(ConfigurableApplicationContext context) {

    }

    @Override
    public void running(ConfigurableApplicationContext context) {

    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }


    /**
     * 设置默认的环境变量
     */
    private void setEnvProps() {

        boolean isWindows = SystemUtils.IS_OS_WINDOWS;
        if (isWindows) {
            System.setProperty(Constant.LOG_PATH, DEFAULT_WINDOS_LOG_PATH);
        } else {
            System.setProperty(Constant.LOG_PATH, DEFAULT_LINUX_LOG_PATH);
        }
        System.setProperty(Constant.LOG_LEVEL, DEFAULT_LOG_LEVEL);
        System.setProperty(Constant.LOG_CONFIG, DEFAULT_LOG_FILE);
    }
}
